<?php
/**
 * CreateTime: 2024/1/15 17:40
 * User:LinQ
 */

namespace App\Func\Customer;

use App\Models\Customers\CustomersModel;
use App\Models\Users\UsersModel;

class CustomerFunc
{

    /**
     * 校验用户签名以及是否切换设备 并且返回当前登录用户的id uuid等
     * @param string $utk 支持手动传入utk
     * @param string $u_dept 支持手动传入用户部门
     * @param bool $canAll 是否显示公私钥
     * @return mixed
     */
    public function getLoginInfo($utk = "",$u_dept = "",$canAll = false): mixed
    {

        if(!$utk){
            $utk = request()->header('U-TK');
        }
        if(!$utk){
            s_fail_return(null,trans('message.auth_checker_err',[
                'code' => 1001
            ]),
                status:false,
                code:'Unauthorized',
                httpCode: 401
            );
        }

        $utkInfo = explode('.',$utk);
        // headerInfo
        $headerInfo = json_decode(base64_decode($utkInfo[0]),true);
        $payloadInfo = json_decode(base64_decode($utkInfo[1]),true);
        $sign = $utkInfo[2];
        $deadline = $headerInfo['deadline'];
        // TODO 暂时注释
//        if(time()>$deadline){
//            s_fail_return(null,'登录已过期,请重新登录',
//                status:false,
//                code:'Unauthorized',
//                httpCode: 401
//            );
//        }
        if($headerInfo['alg'] == 'HS256'){
            $sg = base64_encode(hash_hmac('sha256', "$utkInfo[0].$utkInfo[1].$utkInfo[3]", md5(json_encode($utkInfo[1],true)), true));
        }else{
            $sg = "";
        }
        if($sg!=$sign){
            s_fail_return(null,trans('message.auth_checker_err',[
                'code' => 1002
            ]),
                status:false,
                code:'Unauthorized',
                httpCode: 401
            );
        }
        $ipInfo = aes_256_cbc_pkcs7_decode($utkInfo[3],md5($payloadInfo['user_id']));
        // TODO 暂时注释
//        if($ipInfo!=request()->ip()){
//            s_fail_return(null,trans('message.auth_checker_err',[
//                'code' => 1003
//            ]),
//                status:false,
//                code:'Unauthorized',
//                httpCode: 401
//            );
//        }
        // 校验用户的hash编码是否能够对应
        // 获取用户信息
        $userInfo = CustomersModel::find($payloadInfo['user_id']);
        if($payloadInfo['hash'] != hash_sign_x1($userInfo->password)){
            s_fail_return(null,trans('message.auth_checker_err',[
                'code' => 1004
            ]),
                status:false,
                code:'Unauthorized',
                httpCode: 401
            );
        }
        $userInfoArr = $userInfo->toArray();
        if($canAll){
            $userInfoArr['pv_key'] = $userInfo->pv_key;
            $userInfoArr['pu_key'] = $userInfo->pu_key;
        }
        return $userInfoArr;
    }
}
